package com.swang.security.sdk.integration;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

import com.swang.security.facade.AuthorityFacade;
import com.swang.security.facade.rpc.CommonResult;
import com.swang.security.sdk.LoggerUtils;
import com.swang.security.sdk.SwangGrantedAuthority;

/**
 * @ClassName: SdkAuthorityClient
 * @Description: 用户权限客户端rpc调用
 * @author swang
 * @date 2017年4月22日 上午2:16:52
 */
public class SdkAuthorityClient implements InitializingBean {
	private static final Logger logger = Logger.getLogger(SdkAuthorityClient.class);
	
	private AuthorityFacade authorityFacade;
	
	public List<GrantedAuthority> findAuthoritiesByUserId(Long userId){
		CommonResult<List<String>> authrityResult = authorityFacade.findAuthoritiesByUserId(userId);
		LoggerUtils.debug(logger, "SdkAuthorityClient.findAuthoritiesByUserId入参：{0}", userId);
		LoggerUtils.debug(logger, "返回参数：{0}", authrityResult);
		if (authrityResult == null || !authrityResult.getIsSuccess()) {
			return null;
		} else {
			List<String> authorities = authrityResult.getContent();
			List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
			for (Iterator<String> iterator = authorities.iterator(); iterator.hasNext();) {
				String authority = iterator.next();
				grantedAuthorities.add(new SwangGrantedAuthority(authority));
			}
			return grantedAuthorities;
		}
	}
	
	

	public void setAuthorityFacade(AuthorityFacade authorityFacade) {
		this.authorityFacade = authorityFacade;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(this.authorityFacade, "AuthorityFacade注入不能为空");
	}

}
